package inits

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"srv-server/basic/config"
	"srv-server/basic/global"
)

func init() {
	config.Init()
	InitMysql()
	InitRedis()
}

func InitRedis() {
	appends := config.AppConfig.Redis
	global.Rds = redis.NewClient(&redis.Options{
		Addr:     appends.Host,
		Password: appends.Password, // no password set
		DB:       appends.Db,       // use default DB
	})
	err := global.Rds.Ping(context.Background()).Err()
	if err != nil {
		panic("redis连接失败")
	}

}

func InitMysql() {
	var err error
	appends := config.AppConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", appends.User, appends.Password, appends.Host, appends.Port, appends.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic("mysql连接失败")
	}

}
